#include "TrngInitHelper.h"
#include <stdio.h>

#include <string.h>

uint32_t trng_buf[2];
uint8_t trng_data[8];
uint8_t trng_index = 0;
char trng_str16[16];
char trng_str[128];

void Trng_Init(void) {
  /* Enable TRNG. */
  FCG_Fcg0PeriphClockCmd(FCG0_PERIPH_TRNG, ENABLE);
  /* TRNG initialization configuration. */
  TRNG_Init(TRNG_SHIFT_CNT256, TRNG_RELOAD_INIT_VAL_ENABLE);
}

void TRNG_IrqCallback(void) {
  (void) TRNG_GetRandom(trng_buf, 2U);

  trng_data[0] = trng_buf[0] % 0x100;
  trng_data[1] = (trng_buf[0] >> 8) % 0x100;
  trng_data[2] = (trng_buf[0] >> 16) % 0x100;
  trng_data[3] = (trng_buf[0] >> 24) % 0x100;
  trng_data[4] = trng_buf[1] % 0x100;
  trng_data[5] = (trng_buf[1] >> 8) % 0x100;
  trng_data[6] = (trng_buf[1] >> 16) % 0x100;
  trng_data[7] = (trng_buf[1] >> 24) % 0x100;

  sprintf(trng_str16, "%02X%02X%02X%02X%02X%02X%02X%02X", trng_data[0], trng_data[1], trng_data[2], trng_data[3],
          trng_data[4], trng_data[5], trng_data[6], trng_data[7]);

  //rt_kprintf("get trng16: %s\n", trng_str16);
	if ( strcmp(chip_device_event.parent.parent.name, "chip_device_event") == 0 ) {
		rt_event_send(&chip_device_event, CHIP_DEVICE_EVENT__TRNG_FINISHED);
	}
}

rt_err_t Get_Trng_Wait(rt_int32_t timeout) {
	TRNG_Start();
	rt_uint32_t e;
	if ( rt_event_recv(&chip_device_event, CHIP_DEVICE_EVENT__TRNG_FINISHED, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, timeout, &e) != RT_EOK ){
		rt_kprintf("event error\n");
	}
	return e;
}
